package com.example.flatlafdemo.components.menubar;

import com.example.flatlafdemo.FlatlafDemoApplication;
import com.formdev.flatlaf.*;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;

public class FlatlafMenuBar extends JMenuBar {

    public FlatlafMenuBar() {
        initMenubar();
    }

    private void initMenubar() {
        initFileMenu();
        initViewMenu();
    }

    private void initFileMenu() {
        JMenu fileMenu = new JMenu("File");
        add(fileMenu);
        addMenuItem("Exit", e -> { exitFrame(); },
                KeyStroke.getKeyStroke('Q', Event.CTRL_MASK), fileMenu);
    }

    private void initViewMenu() {
        JMenu viewMenu = new JMenu("View");
        add(viewMenu);

        JMenu lookFeelMenu = new JMenu("Look And Feel");
        viewMenu.add(lookFeelMenu);

        ButtonGroup group = new ButtonGroup();

        addRadioButtonMenuItem("FlatLaf Light", true,
                e -> { lightLookAndFeel(); }, group, lookFeelMenu);
        addRadioButtonMenuItem("FlatLaf Dark", false,
                e -> { darkLookAndFeel(); }, group, lookFeelMenu);
        addRadioButtonMenuItem("FlatLaf IntelliJ", false,
                e -> { intelliJLookAndFeel(); }, group, lookFeelMenu);
        addRadioButtonMenuItem("FlatLaf Darcula", false,
                e -> { darculaLookAndFeel(); }, group, lookFeelMenu);
    }

    private void addMenuItem(String text, ActionListener listener, KeyStroke keyStroke,
                             JMenu parentMenu) {
        JMenuItem menuItem = new JMenuItem(text);
        menuItem.addActionListener(listener);
        menuItem.setAccelerator(keyStroke);
        parentMenu.add(menuItem);
    }

    private void addRadioButtonMenuItem(String text, boolean selected, ActionListener listener,
                                        ButtonGroup group, JMenu parentMenu) {
        JRadioButtonMenuItem menuItem = new JRadioButtonMenuItem(text);
        menuItem.addActionListener(listener);
        menuItem.setSelected(selected);
        group.add(menuItem);
        parentMenu.add(menuItem);
    }

    private void exitFrame() {
        System.exit(1);
    }

    private void lightLookAndFeel() {
        flatLafLookAndFeel(new FlatLightLaf());
    }

    private void darkLookAndFeel() {
        flatLafLookAndFeel(new FlatDarkLaf());
    }

    private void intelliJLookAndFeel() {
        flatLafLookAndFeel(new FlatIntelliJLaf());
    }

    private void darculaLookAndFeel() {
        flatLafLookAndFeel(new FlatDarculaLaf());
    }

    private void flatLafLookAndFeel(FlatLaf flatLaf) {
        try {
            UIManager.setLookAndFeel(flatLaf);
            if (FlatlafDemoApplication.frame != null) {
                SwingUtilities.updateComponentTreeUI(FlatlafDemoApplication.frame);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
